import json
import sys
import flet as ft
import pdf2docx
import subprocess
import xlrd
import xlwt
import pdfplumber
import re
import PyPDF2
import os
import time
from utils import snack_bar, DESKTOP
from views.treasure_dialogs.base import BaseDialog
from methods.getcovareas import get_risk_area_data
from settings import BASE_DIR


class Dialog(BaseDialog):
    def __init__(self):
        self.province_dd = ft.Dropdown(
            options=[],
            width=200,
            height=40,
            content_padding=5,
            on_change=lambda e: self.change_province_event(e.data),
        )
        self.city_dd = ft.Dropdown(
            options=[],
            width=200,
            height=40,
            content_padding=5,
            on_change=lambda e: self.change_city_event(e.data),
        )
        self.county_dd = ft.Dropdown(
            options=[],
            width=200,
            height=40,
            content_padding=5,
            on_change=lambda e: self.change_county_event(e.data),
        )
        self.select_component = ft.Row([self.province_dd, self.city_dd, self.county_dd])

        self.data_table = ft.DataTable(
            columns=[ft.DataColumn(ft.Text("名称")), ft.DataColumn(ft.Text("风险等级"))], width=600
        )
        self.close_btn = ft.IconButton(
            icon=ft.icons.CLOSE_OUTLINED, on_click=self.close_dlg
        )
        self.area_data = {}
        self.end_update_time = ""
        self.title_text = ft.Text()

        # pdf2excel start .........
        # 进度条
        self.pdfHandleProgressBar = ft.ProgressBar(visible=False, width=600, height=20, color="amber", bgcolor="#eeeeee")
        self.pdfHandleProgressInfo = ft.Text(visible=True,
                                             value="未开始",
                                             size=50,
                                             color=ft.colors.SHADOW,
                                             bgcolor=ft.colors.ORANGE_800,
                                             weight=ft.FontWeight.NORMAL,
                                             text_align='center'
                                             )
        # 帮组信息
        self.hint = ft.Text(
            "*********************************************************************************\n"
            "*********************************************************************************\n"
            "·          PdfToExcel copyright@2024 GZH\n"
            "·          disclaimer: 本软件仅供技术交流使用，请勿用于商业用途。\n"
            "·          firstStep: 请选择需要解析的pdf所在的文件夹\n"
            "·          secondStep: 选择解析Pdf所需要的源码\n"
            "·          thirdStep: 点击启动，等待解析完成\n"
            "·          And : 可以自己手动上传源码，但请确保源码正确无误。源码存放位置默认为：D:\\yu_pan_source_py\n"
            "*********************************************************************************\n"
            "*********************************************************************************\n"
        )

        # 选择文件夹
        self.choose_folder_dialog = None
        self.choose_folder_btn = ft.FloatingActionButton(
            "请选择pdf所在文件夹", on_click=self.open_choose_folder_dialog, width=800
        )
        self.upload_source_dialog = None
        self.upload_source_py_btn = ft.FloatingActionButton(
            "请上传第三方源码", on_click=self.upload_source_py, width=800, bgcolor='#ffd866'
        )

        # 选择源码文件
        # width=200,
        self.source_py_dd = ft.Dropdown(
            label="源码",
            hint_text="请选择要使用的源码",
            options=[],
            height=40,
            content_padding=5,
            on_change=lambda e: self.change_source_py(e.data),
        )
        # self.choose_source_py_row = ft.Row([self.source_py_dd,])
        # 开始执行
        self.submit_btn = ft.FloatingActionButton(
            "启动", on_click=self.startHandleFile, width=800, height=40, autofocus=True
        )
        super(Dialog, self).__init__(
            title=ft.Text("PdfToExcel copyright@2024 GZH"),
            content=ft.Stack(
                [ft.Column([self.choose_folder_btn,
                            self.source_py_dd,
                            self.pdfHandleProgressBar,
                            self.submit_btn,
                            self.upload_source_py_btn,
                            self.pdfHandleProgressInfo,
                            self.hint
                            ])
                 ],
                width=700,
                expand=True,
            ),
            content_padding=20,
            actions=[self.close_btn],
            actions_alignment="center",
        )

    def open_dlg(self, e):
        super().open_dlg(e)
        data = get_risk_area_data()
        self.init_source_py_options()

        if data[1] != 200:
            self.title_text.value = "抱歉，查询接口出错！"
        else:
            try:
                self.format_data(data[0])
                self.title_text.value = self.end_update_time
                provinces = list(self.area_data.keys())
                self.province_dd.options.extend([ft.dropdown.Option(i) for i in provinces])
                self.province_dd.value = provinces[0]
                self.change_province_event(provinces[0])
            except Exception as e:
                pass
        self.update()

    def format_data(self, data):
        # province-> city-> county-> communitys ->level
        try:
            self.end_update_time = data["data"]["end_update_time"]
            details = data["data"]
            mark = {"highlist": "高风险区域", "middlelist": "中风险区域", "lowlist": "低风险区域"}
            for list_name, level in mark.items():
                for h in details[list_name]:
                    if h["province"] not in self.area_data:
                        self.area_data[h["province"]] = {}
                    province = self.area_data[h["province"]]
                    if h["city"] not in province:
                        province[h["city"]] = {}
                    city = province[h["city"]]
                    if h["county"] not in city:
                        city[h["county"]] = {}
                    county = city[h["county"]]
                    for community in h["communitys"]:
                        county[community] = level
        except Exception as e:
            pass

    def change_province_event(self, province):
        self.province_dd.value = province
        cities = list(self.area_data[province].keys())
        self.city_dd.options.clear()
        self.city_dd.options.extend([ft.dropdown.Option(i) for i in cities])
        self.change_city_event(cities[0])

    def change_city_event(self, city):
        self.city_dd.value = city
        province = self.province_dd.value
        counties = list(self.area_data[province][city].keys())
        self.county_dd.options.clear()
        self.county_dd.options.extend([ft.dropdown.Option(i) for i in counties])
        self.change_county_event(counties[0])

    def change_county_event(self, county):
        self.county_dd.value = county
        province = self.province_dd.value
        city = self.city_dd.value
        self.data_table.rows.clear()
        for position, level in self.area_data[province][city][county].items():
            row = ft.DataRow(
                cells=[
                    ft.DataCell(ft.Text(position, width=400, overflow="clip")),
                    ft.DataCell(ft.Text(level))
                ]
            )
            if level == "高风险区域":
                row.color = ft.colors.RED_50
            elif level == "中风险区域":
                row.color = ft.colors.PINK_50
            elif level == "低风险区域":
                row.color = ft.colors.YELLOW_50
            self.data_table.rows.append(row)

        self.update()

    def open_choose_folder_dialog(self, e):
        if self.choose_folder_dialog is None:
            self.choose_folder_dialog = ft.FilePicker(on_result=self.pdfFolderResult)
            self.page.overlay.append(self.choose_folder_dialog)
            self.page.update()
        self.choose_folder_dialog.get_directory_path(dialog_title="选择pdf所在文件夹", )

    def pdfFolderResult(self, e: ft.FilePickerResultEvent):
        if e.path is not None:
            self.choose_folder_btn.text = e.path
        self.page.update()

    def init_source_py_options(self):
        self.source_py_dd.options.clear()
        # current_py_dir = os.path.dirname(os.path.abspath(__file__))
        # current_py_dir = current_py_dir.replace(r'\views\treasure_dialogs', '')
        source_py_list = self.get_yupan_dir()
        for file in os.listdir(source_py_list):
            if file.endswith('.py') and file != '__init__.py':
                self.source_py_dd.options.append(ft.dropdown.Option(file))
        self.page.update()

    def change_source_py(self, source_py):
        self.page.update()

    def startHandleFile(self, e):
        if self.choose_folder_btn.text == '请选择pdf所在文件夹':
            snack_bar(self.page, "请先选择pdf所在文件夹")
            return
        if self.source_py_dd.value == '源码':
            snack_bar(self.page, "请先选择源码文件")
            return
        snack_bar(self.page, "正在处理请稍候")
        self.pdfHandleProgressBar.visible = True
        self.pdfHandleProgressInfo.value = "正在处理..."
        self.page.update()
        pdf_folder = self.choose_folder_btn.text
        source_py = self.source_py_dd.value
        yupan_dir = self.get_yupan_dir()
        source_py = yupan_dir + f'\{source_py}'
        try:
            with open(source_py, "rb") as f:
                os.chdir(pdf_folder)
                source_code = f.read()
                exec(source_code)
        except Exception as e:
            snack_bar(self.page, f"执行出错：{e}")
        finally:
            self.pdfHandleProgressBar.visible = False
            self.pdfHandleProgressInfo.value = "已完成..."
            self.page.update()
            pass
        snack_bar(self.page, "处理完成")

    def get_yupan_dir(self):
        yupan_dir = os.path.join(BASE_DIR, 'yu_pan_source_py')
        # 不存在则创建
        if not os.path.exists(yupan_dir):
            os.makedirs(yupan_dir)
        return yupan_dir

    def upload_source_py(self, e):
        if self.upload_source_dialog is None:
            self.upload_source_dialog = ft.FilePicker(on_result=self.save_source_py)
            self.page.overlay.append(self.upload_source_dialog)
            self.page.update()
        self.upload_source_dialog.pick_files(dialog_title="选择pdf", file_type="any")

    def save_source_py(self, e: ft.FilePickerResultEvent):
        yupan_dir = self.get_yupan_dir()
        if e.data:
            data = json.loads(e.data)
            if data["files"]:
                file_path = data["files"][0]["path"]
                if not file_path.endswith("py"):
                    snack_bar(self.page, "请选择python源码文件")
                else:
                    self.close_dlg(None)
                    self.page.splash.visible = True
                    self.page.update()
                    file_name = os.path.basename(file_path)
                    # 复制file_path到yupan_dir
                    new_file_path = os.path.join(yupan_dir, file_name)
                    with open(file_path, "rb") as f:
                        with open(new_file_path, "wb") as f2:
                            f2.write(f.read())
                    # 刷新下拉框
                    self.init_source_py_options()
                    self.page.splash.visible = False
                    self.page.update()
                    snack_bar(self.page, f"源码已经上传成功，请刷新页面")
